package com.spring.ssm.controller;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Array;
import java.util.Arrays;


/**
 * @author canger
 * @Deseription web层的日志切面类
 * @create 2018/8/23 11:29
 **/
@Aspect
@Component
public class WebLogAspect {

   private Logger logger = Logger.getLogger(getClass());

    @Pointcut("execution(public * com.spring.ssm..*.*(..))")
    public void webLog(){

    }
    @Before("webLog()")
    public  void doBegore(JoinPoint joinPoint){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        logger.info("访问URL:"+request.getRequestURL().toString());
        logger.info("访问方法:"+request.getMethod());
        logger.info("访问ip:"+request.getRemoteAddr());
        //获取访问类的class和方法
        logger.info("访问ip:"+joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName());
        //获取访问时的参数和值
        logger.info("args:"+ Arrays.toString(joinPoint.getArgs()));


    }
    @AfterReturning(returning = "ret",pointcut = "webLog()")
    public  void doAfter(Object ret){
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        logger.info("返回对象:"+ret);
    }
    @AfterThrowing(pointcut = "webLog()",throwing = "e")
    public  void doThrowing(Throwable  e){
        logger.error("error",e);
    }
}
